package geoapi

import (
	"encoding/json"
	"errors"
)

// dbip
type dbipResp struct {
	CountryCode string `json:"countryCode"`
	CountryName string `json:"countryName"`
	StateProv   string `json:"stateProv"`
	City        string `json:"city"`
	ErrorCode   string `json:"errorCode"`
	Error       string `json:"error"`
}

// GeoDBIP 请求 http://api.db-ip.com/v2/free/ api
// http://api.db-ip.com/v2/free/xx.xx.xx.xx
func GeoDBIP(host string) (ig IPGeo, err error) {
	uri := `http://api.db-ip.com/v2/free/` + host
	data, err := getApiData(uri)
	if err != nil {
		return
	}
	var t dbipResp
	err = json.Unmarshal(data, &t)
	if err != nil {
		return
	}
	if t.ErrorCode != "" {
		err = errors.New(t.Error)
		return
	}
	ig.City = t.City
	ig.CountryCode = t.CountryCode
	ig.CountryName = t.CountryName
	ig.Query = host
	ig.StateProv = t.StateProv
	ig.Status = "success"
	return
}
